//
//  OrderDetailViewController.swift
//  ShareCar
//
//  Created by 久众科技 on 2018/7/10.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import Foundation
import MAMapKit

enum Movement: String {
    case cancelOrder = "cancel"      //取消订单
    case detailOrder = "detail"      //支付订单
    case debtOrder   = "orderDebt"   //欠款订单
}

class OrderDetailViewController: UIViewController {
    
    var orderId : String!       //当前订单id
    var page : Movement!
    
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var mapView: MAMapView!
    @IBOutlet weak var topFourLabel: UILabel!
    @IBOutlet weak var topThreeLabel: UILabel!
    @IBOutlet weak var topTwoLabel: UILabel!
    @IBOutlet weak var topOneLabel: UILabel!
    
    @IBOutlet weak var carImageView: UIImageView!
    
    @IBOutlet weak var bottomOneLabel: UILabel!
    @IBOutlet weak var bottomTwoLabel: UILabel!
    @IBOutlet weak var bottomThreeLabel: UILabel!
    @IBOutlet weak var bottomFourLabel: UILabel!
    
    @IBOutlet weak var bottomFiveLabel: UILabel!
    @IBOutlet weak var bottomSexLabel: UILabel!
    @IBOutlet weak var orderSnLabel: UILabel!
    
    @IBOutlet weak var orderDetailView: UIView!
    var data : User.orderInfo?
    
    
    
    var pathPolyLines = [CLLocationCoordinate2D]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        mapView.config()
        mapView.showsUserLocation = false
        mapView.delegate = self
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        let title = page == .debtOrder ? "去支付" : "申诉/投诉"
        let rightButton = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(complain))
        if page == .debtOrder {
            rightButton.tintColor = UIColor(hexString: "ff7517")
        }
        
        navigationItem.rightBarButtonItem = rightButton
        
        if let p = page {
            switch p {
            case .cancelOrder :
                topThreeLabel.isHidden = true
                topFourLabel.isHidden = true
            case .detailOrder:
                topThreeLabel.isHidden = false
                topFourLabel.isHidden = false
            case .debtOrder:
                bottomFiveLabel.isHidden = false
                bottomSexLabel.isHidden = false
            }
        }
        
        JZLoading.showLoadingWith(toView: self.view)
        User.getOrderDetailInfo(orderId: orderId, success: { [weak self] data in
            JZLoading.hideLoading()
            self?.data = data
            self?.setup()
            self?.walkingRouts()
            self?.addAnnotation()
            
        }) { message in
            JZLoading.hideLoading()
            XHProgressHUD.showError(message.msg)
        }

    }
    
    func setup(){
        if let data = self.data {
            topOneLabel.text = data.plateNumber
            topTwoLabel.text = data.carTypeName
            timeLabel.text = Date.timeStampToString(timeStamp: data.addTime)
            if let distance = data.drivingDistance {
                let dis = Int(ceil(Double(distance) / 1000.0))
                topThreeLabel.text = "\(dis)公里"
            }
            
            if let duration = data.drivingDuration {
                topFourLabel.text = "\(duration)分钟"
            }
            
            if let value = data.debtMoney {
                if page == .debtOrder {
                    bottomSexLabel.text = "\(value)元"
                } else {
                    bottomFiveLabel.isHidden = true
                    bottomSexLabel.isHidden = true
                }
            } else {
                bottomFiveLabel.isHidden = true
                bottomSexLabel.isHidden = true
            }
            
            if let orderSn = data.orderSn {
                orderSnLabel.text = "订单号:\(orderSn)"
            }
            
            bottomOneLabel.text = data.totalMoney + "元"
            bottomTwoLabel.text = data.discountMoney + "元"
            bottomThreeLabel.text = data.money + "元"
            
            let payType = data.payMethod == 0 ? "未支付" :
                          data.payMethod == 1 ? "支付宝支付":
                          data.payMethod == 2 ? "微信支付":
                          data.payMethod == 4 ? "Apple Pay":
                          data.payMethod == 6 ? "余额支付" : "系统免单"
            
            bottomFourLabel.text = payType
            let url = URL(string: kImageServerName + data.imagePath)
            carImageView.kf.setImage(with: url)
            
            view.addSubview(orderDetailView)
            
            orderDetailView.snp.makeConstraints { make in
                
                var constrans = 0
                if let p = page {
                    switch p {
                    case .cancelOrder: constrans = 116
                    case .detailOrder: constrans = 197
                    case .debtOrder: constrans = 236
                    }
                }
                make.left.right.bottom.equalTo(0)
                make.height.equalTo(constrans)
            }
        }
    }
    
    @objc func complain(){
        
        if page == .debtOrder {
            //已欠款跳支付
            performSegue(withIdentifier: "unPayorderSence", sender: data?.debtMoney)
        } else {
            performSegue(withIdentifier: "judgecomplainSence", sender: self)
        }
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        if segue.identifier == "judgecomplainSence" {
            if let controller = segue.destination as? ComplainViewController {
                controller.data = data
                controller.orderId = orderId
            }
        } else if(segue.identifier == "unPayorderSence") {
            if let controller = segue.destination as? PayDepositViewController {
                if let debtMoney = data?.debtMoney, let paySwitch = data?.balanceFlag {
                    controller.numberInfPay = Double(debtMoney)!
                    controller.orderId = orderId
                    controller.needAcccountPay = paySwitch
                    controller.workType = .payOrder
                }
            }
        }
    }
    
    func walkingRouts() {
        guard let path = self.data?.drivingPath, path.count > 0 else {
            return
        }
        
        pathPolyLines.removeAll()
        
        for i in path {
            let loc = CLLocationCoordinate2D(latitude: i[1], longitude: i[0])
            pathPolyLines.append(loc)
        }
        
        if let poly = MAPolyline(coordinates: &pathPolyLines, count: UInt(pathPolyLines.count)) {
            self.mapView.add(poly)
            self.mapView.showOverlays([poly], animated: false)
        }
    }
    
    func addAnnotation() {
        guard let path = self.data?.drivingPath, path.count > 0 else {
            return
        }
        
        guard let first = path.first else {
            return
        }
        
        guard let last = path.last else {
            return
        }
        
        let start = CLLocationCoordinate2D(latitude: first[1], longitude: first[0])
        
        let end = CLLocationCoordinate2D(latitude: last[1], longitude: last[0])
        
        let startAnnotation = StartAnnotation()
        startAnnotation.coordinate = start
        self.mapView.addAnnotation(startAnnotation)
        
        let endAnnotation = EndAnnotation()
        endAnnotation.coordinate = end
        self.mapView.addAnnotation(endAnnotation)
    }
}

extension OrderDetailViewController: MAMapViewDelegate {
    func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
        let lineColor = UIColor(red: 255.0 / 255.0, green: 117.0 / 255.0, blue: 23.0 / 255.0, alpha: 1.0)
        if overlay.isKind(of: MAPolyline.self) {
            
            guard let polyline = MAPolylineRenderer(overlay: overlay) else {
                return nil
            }
            
            polyline.lineWidth = 6.0
            polyline.strokeColor = lineColor
            polyline.fillColor = lineColor
            polyline.lineJoinType = kMALineJoinRound
            polyline.lineCapType = kMALineCapRound
            
            return polyline
        }
        
        return nil
    }
    
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        
        let startIndetifier = "start_indetifier"
        let endIndetifier = "end_indetifier"
        
        if annotation.isKind(of: MAUserLocation.self) {
            return nil
        }
        
        if annotation.isKind(of: StartAnnotation.self) {
            var annotationView: MAAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: startIndetifier)
            
            if annotationView == nil {
                annotationView = MAAnnotationView(annotation: annotation, reuseIdentifier: startIndetifier)
            }
            
            annotationView!.image = UIImage(named: "ann_start")
            annotationView!.centerOffset = CGPoint(x: 0, y: -12)
            
            return annotationView!
        }
        
        if annotation.isKind(of: EndAnnotation.self) {
            var annotationView: MAAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: endIndetifier)
            
            if annotationView == nil {
                annotationView = MAAnnotationView(annotation: annotation, reuseIdentifier: endIndetifier)
            }
            
            annotationView!.image = UIImage(named: "ann_end")
            annotationView!.centerOffset = CGPoint(x: 0, y: -12)
            
            return annotationView!
        }
        
        return nil
    }
}
